package com_.dxy_test_.async_;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * @Description 测试Future和Callable多线程等待结果返回
 * @Author dangxianyue
 * @Date 2022/11/3 9:52
 */
public class FutureCallableTest {
    public static void main(String[] args) {
        FutureCallableTest test = new FutureCallableTest();
        String s1 = null, s2 = null;
        long start = System.currentTimeMillis();

        //同步调用的当时，耗时：3024
        //s1 = test.f1();
        //s2 = test.f2();

        //多线程异步调用，耗时：2040（以最久的方法为准）
        ExecutorService pool = Executors.newFixedThreadPool(10);
        Future<String> future1 = pool.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                return test.f1();
            }
        });

        Future<String> future2 = pool.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                return test.f2();
            }
        });


        try {
            s1 = future1.get();
            s2 = future2.get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }

        pool.shutdown();

        System.out.println(s1 + ", " + s2);
        System.out.println("耗时：" + (System.currentTimeMillis() - start));

    }

    private String f1() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "你好";
    }

    private String f2() {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "张三";
    }
}
